import axios, { AxiosHeaders } from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { useUserStore } from '@/stores/user'

// Extend AxiosRequestConfig to include custom options
interface CustomRequestConfig extends AxiosRequestConfig {
  requireToken?: boolean
}

const service: AxiosInstance = axios.create({
  baseURL: '/dev',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// Request interceptor
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStore()
    
    // 如果明确不需要token，则不添加
    if ((config as CustomRequestConfig).requireToken === false) {
      return config
    }
    
    // 如果有token，则添加到请求头
    if (userStore.token) {
      const headers = new AxiosHeaders(config.headers)
      headers.set('Authorization', `Bearer ${userStore.token}`)
      config.headers = headers
    }
    
    return config
  },
  (error: any) => {
    return Promise.reject(error)
  }
)

// Response interceptor
service.interceptors.response.use(
  (response: AxiosResponse): any => {
    const { data } = response
    if (data.code === 1001) {
      const userStore = useUserStore()
      if (window.location.pathname !== '/login' && data.message.indexOf('登录') > -1) {
        userStore.clearToken()
        window.location.href = '/login'
      }
      return Promise.reject(data.message)
    }
    return data
  },
  (error: any) => {
    // 处理401未授权错误
    if (error.response?.status === 401) {
      const userStore = useUserStore()
      userStore.clearToken()
      // 可以在这里添加重定向到登录页的逻辑
    }
    return Promise.reject(error)
  }
)

// Create typed request methods
const request = {
  get: <T = any>(url: string, config?: AxiosRequestConfig): Promise<T> => {
    return service.get(url, config)
  },
  post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
    return service.post(url, data, config)
  },
  put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
    return service.put(url, data, config)
  },
  delete: <T = any>(url: string, config?: AxiosRequestConfig): Promise<T> => {
    return service.delete(url, config)
  }
}

export default request 